﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using TFSTools.TFSLibrary.TestManagement;

namespace TFSTools.WpfControls
{
    public class TestSuiteTreeViewItemsBuilder : TreeViewItemsBuilder
    {
        private TFSTestPlan tfsTestPlan;

        public TestSuiteTreeViewItemsBuilder(TFSTestPlan testPlan)
            : base(testPlan.Connection)
        {
            this.tfsTestPlan = testPlan;
        }

        public bool IgnoreSuitesWithoutTestCases { get; set; }

        public override void PopulateTreeView(TreeView treeView)
        {
            var rootSuite = this.tfsTestPlan.RootSuite;

            this.BuildTreeViewNodesFromSuite(rootSuite, treeView.Items);
        }

        private void BuildTreeViewNodesFromSuite(TFSTestSuite suite, ItemCollection parentItems)
        {
            bool hasSubSuites = suite.SubSuites.Any();

            if (!hasSubSuites && this.IgnoreSuitesWithoutTestCases && suite.TestCaseCount == 0) { return; }

            var newItem = new TreeViewItem()
            {
                Header = suite.Title,
                Tag = suite,
                IsExpanded = IsExpanded
            };

            parentItems.Add(newItem);

            if (suite.SubSuites.Any())
            {
                var newItems = newItem.Items;
                
                foreach (var subSuite in suite.SubSuites)
                {
                    this.BuildTreeViewNodesFromSuite(subSuite, newItems);
                }

                if (newItems.CanSort)
                {
                    newItems.SortDescriptions.Add(new SortDescription("Header", ListSortDirection.Ascending));
                }
            }
        }
    }
}
